package com.lottery.ruok.lottrey.activity;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.text.Html;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.adapter.BetListAdapter;
import com.lottery.ruok.lottrey.bean.OrderObservableList;
import com.lottery.ruok.lottrey.dialog.OrderSetDialog;
import com.lottery.ruok.lottrey.eventbusObject.AddBetList;
import com.lottery.ruok.lottrey.eventbusObject.AddBetSuccess;
import com.lottery.ruok.lottrey.eventbusObject.ModifyBetOrder;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.CreateOrderRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.GetCurrentIssueNoRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.CreateOrderResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.GetCurrentIssueNoResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.GetLotteryDetailResponse;
import com.lottery.ruok.lottrey.ui.BottomButtonModule;
import com.lottery.ruok.lottrey.userInfo.UserInfo;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import count_down.CountDownManager;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;
import kotlin.jvm.functions.Function1;
import ui.IToast;
import ui.IToastAddBet;
import utils.Utils;
/*
* 投注单
* */

public class BetListActivity extends BaseActivity {
    @BindView(R.id.listView)
    ListView listView;
    @BindView(R.id.time)
    TextView time;
    @BindView(R.id.random)
    LinearLayout random;
    @BindView(R.id.webview)
    WebView webview;
    @BindView(R.id.money)
    TextView money;
    @BindView(R.id.delete)
    TextView delete;

    public final static String ANALYTIC_VERSION = "1.0";
    private String currentNo;
    public static OrderObservableList<Result> results = new OrderObservableList<>();
    public static Result lastResult;//记录最新手选的一注，用于生成随机注数
    private BetListAdapter betListAdapter;
    float sumMoney;
    private BottomButtonModule mBottomButtonModule;
    public ArrayList<Float> recordMoneyList;
    private CountDownManager.CountDownModel countDownModel;
    private GetCurrentIssueNoResponse currentIssueNoData;

    @OnClick(R.id.delete)
    public void onViewClicked() {
        Utils.createDialog(this, "是否要全部删除", "是", "否", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                results.clear();
                if (betListAdapter != null) {
                    betListAdapter.notifyDataSetChanged();
                }

                setMoney();
            }
        }, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
    }

    @OnClick(R.id.random)
    public void onViewClicked1() {
        //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_betrecord_random_add");

        if (lastResult != null) {
            createOneBet();
        }
    }

    private void createOneBet() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("need_row", lastResult.childrenBean.getNeed_row());
            jsonObject.put("need_number", lastResult.childrenBean.getNeed_number());
            jsonObject.put("multiple", lastResult.childrenBean.getMultiple());
            jsonObject.put("input", lastResult.childrenBean.getInput());
            if (lastResult.childrenBean.getNotes() != null) {
                jsonObject.put("notes", new JSONObject(lastResult.childrenBean.getNotes()));
            } else {
                jsonObject.put("notes", lastResult.childrenBean.getNotes());
            }
            jsonObject.put("checkboxs", lastResult.childrenBean.getCheckboxs());
            jsonObject.put("rule_id", lastResult.childrenBean.getRule_id());
            jsonObject.put("max_odds", lastResult.childrenBean.getMax_odds());
            if (getIntent().getStringExtra("code").equals("gd11x5") || getIntent().getStringExtra("code").equals("bjpk10")) {
                jsonObject.put("is_special", 1);
            } else {
                jsonObject.put("is_special", 0);
            }
            jsonObject.put("layout_code", getIntent().getStringExtra("layout_code"));
            if (lastResult.childrenBean.getSelects() != null) {
                JSONArray jsonArray = new JSONArray();
                for (GetLotteryDetailResponse.LayoutsBean.ChildrenBeanX.ChildrenBean.SelectsBean selectsBean : lastResult.childrenBean.getSelects()) {
                    JSONObject jsonObject1 = new JSONObject();
                    JSONArray jsonArray1 = new JSONArray(selectsBean.getContent());
                    jsonObject1.put("content", jsonArray1);
                    jsonArray.put(jsonObject1);
                }
                jsonObject.put("selects", jsonArray.toString());
            } else {
                jsonObject.put("selects", "{}");
            }
            jsonObject.put("item_code", getIntent().getStringExtra("code"));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        String t = jsonObject + "," + getIntent().getStringExtra("getNumber_repeat") + "," + getIntent().getStringExtra("getNumber_format") + ",'" + getIntent().getStringExtra("getNumber_range") + "'";
        String func = "javascript:generate_item(" + t + ")";
        webview.loadUrl(func);
    }

    @JavascriptInterface
    public void getRandomString(final String notes, final int counts) {
        if (counts != 0) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    String resultString = notes;
                    if (lastResult.childrenBean.getInput().equals("1")) {
                        if (getIntent().getStringExtra("code").equals("ahk3") || getIntent().getStringExtra("code").equals("jiangsuk3")) {
                            if ("ertonghao_ertonghaodanxuan_shoudongxuanhao".equals(getIntent().getStringExtra("layout_code"))) {
                                //取前两个字符，并把第一个字符复制一遍
                                resultString = resultString.charAt(0) + resultString;
                                resultString = resultString.substring(0, resultString.length() - 1);
                            }
                        }
                    } else {//竖线隔开是行，逗号隔开在一个行里。
                        if (getIntent().getStringExtra("code").equals("ahk3") || getIntent().getStringExtra("code").equals("jiangsuk3")) {
                            if ("ertonghao_ertonghaodanxuan_biaozhunxuanhao".equals(getIntent().getStringExtra("layout_code"))) {
                                if (resultString != null) {
                                    resultString = resultString.substring(1, resultString.length());
                                }
                            }
                        }
                    }

                    StringBuilder positions = new StringBuilder("");
                    if (lastResult.childrenBean.getCheckboxs() != null) {
                        int notesLength;//随机选择长度为notesLength的checkboxs
                        if (notes.contains(",")) {
                            notesLength = notes.split(",").length;
                        } else {
                            notesLength = notes.length();
                        }
                        int[] a = new int[]{1, 2, 3, 4, 5};
                        Utils.combine(a, notesLength);
                        if (Utils.results.size() > 0) {
                            int t = Utils.getRandom(0, Utils.results.size());
                            int[] checks = Utils.results.get(t);
                            for (int index : checks) {
                                switch (index) {
                                    case 1:
                                        if (positions.toString().equals("")) {
                                            positions.append("万位");
                                        } else {
                                            positions.append(",").append("万位");
                                        }
                                        break;
                                    case 2:
                                        if (positions.toString().equals("")) {
                                            positions.append("千位");
                                        } else {
                                            positions.append(",").append("千位");
                                        }
                                        break;
                                    case 3:
                                        if (positions.toString().equals("")) {
                                            positions.append("百位");
                                        } else {
                                            positions.append(",").append("百位");
                                        }
                                        break;
                                    case 4:
                                        if (positions.toString().equals("")) {
                                            positions.append("十位");
                                        } else {
                                            positions.append(",").append("十位");
                                        }
                                        break;
                                    case 5:
                                        if (positions.toString().equals("")) {
                                            positions.append("个位");
                                        } else {
                                            positions.append(",").append("个位");
                                        }
                                        break;
                                }
                            }
                        }
                        resultString = positions + "|" + resultString;
                    }

                    try {
                        Result result = lastResult.clone();
                        result.show_results = resultString;
                        result.result = notes;
                        result.checkbox_string = positions.toString();
                        result.num = counts;
                        result.money = result.num * result.amount_per_note;
                        if (getIntent().getStringExtra("code").equals("ahk3") || getIntent().getStringExtra("code").equals("jiangsuk3")) {
                            if ("hezhi_hezhi_hezhi".equals(getIntent().getStringExtra("layout_code"))) {
                                String[] re = result.result.split(",");
                                List<String> keyList = new ArrayList<String>(result.max_odds.keySet());
                                result.odds = null;
                                String[] temp = getIntent().getStringExtra("odds").split(",");
                                for (String aRe : re) {
                                    int index = keyList.indexOf(aRe);
                                    if (result.odds == null) {
                                        result.odds = temp[index];
                                    } else {
                                        result.odds = result.odds + "," + temp[index];
                                    }
                                }
                            }
                        }

                        results.add(result);
                        recordMoneyList.add(result.amount_per_note);
                        betListAdapter.notifyDataSetChanged();
                        setMoney();

                        Utils.showToast("已成功添加一注");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    public static class Result implements Cloneable {//深拷贝
        public String name;
        public int num;
        public float money;
        public String result;
        public String rule_id;
        public String checkbox_string;
        public float amount_per_note;
        public String rakeback;
        public String odds;
        public String show_results;
        public GetLotteryDetailResponse.LayoutsBean.ChildrenBeanX.ChildrenBean childrenBean;
        public float max_rakeback;
        public LinkedHashMap max_odds;
        public LinkedHashMap theory_odds;
        public float max_profit;
        public String min_profit;
        public float min_rakeback;

        @Override
        protected Result clone() {//childrenBean不需要拷贝
            Result result = new Result();
            result.name = name;
            result.result = this.result;
            result.rule_id = rule_id;
            result.checkbox_string = checkbox_string;
            result.rakeback = rakeback;
            result.odds = odds;
            result.show_results = show_results;
            result.num = 1;
            result.money = result.num * amount_per_note;
            result.amount_per_note = amount_per_note;
            result.max_rakeback = max_rakeback;
            result.max_odds = new LinkedHashMap(max_odds);
            result.theory_odds = new LinkedHashMap(theory_odds);
            result.max_profit = max_profit;
            if (min_profit != null) {
                result.min_profit = min_profit;
            }
            result.min_rakeback = min_rakeback;

            return result;
        }
    }

    @OnClick(R.id.aptitudeLottery)
    public void aptitudeLottery() {
        //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_betrecord_autoadd_jump");

        if (sumMoney != 0) {
            Intent intent = new Intent(BetListActivity.this, AptitudeLotteryActivity.class);
            intent.putExtra("code", getIntent().getStringExtra("code"));
            intent.putExtra("money", sumMoney);
            intent.putExtra("no", getIntent().getLongExtra("no", 0));
            startActivity(intent);
        } else {
            Utils.showToast("请选择号码");
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bet_list);

        ButterKnife.bind(this);

        init();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(AddBetSuccess event) {
        setMoney();

        finish();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvents(ModifyBetOrder event) {
        results.get(event.getPosition()).money = event.getMoney();
        results.get(event.getPosition()).rakeback = event.getRakeBack();
        results.get(event.getPosition()).odds = event.getOdds();
        results.get(event.getPosition()).amount_per_note = event.getAmount_per_note();
        if (getIntent().getStringExtra("code").equals("ahk3") || getIntent().getStringExtra("code").equals("jiangsuk3")) {
            if ("hezhi_hezhi_hezhi".equals(getIntent().getStringExtra("layout_code"))) {
                String[] re = results.get(event.getPosition()).result.split(",");
                List<String> keyList = new ArrayList<String>(results.get(event.getPosition()).max_odds.keySet());
                results.get(event.getPosition()).odds = null;
                String[] temp = getIntent().getStringExtra("odds").split(",");
                for (String aRe : re) {
                    int index = keyList.indexOf(aRe);
                    if (results.get(event.getPosition()).odds == null) {
                        results.get(event.getPosition()).odds = temp[index];
                    } else {
                        results.get(event.getPosition()).odds = results.get(event.getPosition()).odds + "," + temp[index];
                    }
                }
            }
        }

        betListAdapter.notifyDataSetChanged();

        setMoney();
    }

    private void addBet() {
        JSONArray jsonArray = new JSONArray();
        for (Result result : results.getList()) {
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("rule_id", result.rule_id);

                String re;
                if (getIntent().getStringExtra("code").equals("gd11x5") || getIntent().getStringExtra("code").equals("bjpk10")) {
                    re = result.result
                            .replaceAll("01", "1")
                            .replaceAll("02", "2")
                            .replaceAll("03", "3")
                            .replaceAll("04", "4")
                            .replaceAll("05", "5")
                            .replaceAll("06", "6")
                            .replaceAll("07", "7")
                            .replaceAll("08", "8")
                            .replaceAll("09", "9");
                } else {
                    re = result.result;
                }

                jsonObject.put("pick_number", re);
                jsonObject.put("position", result.checkbox_string);
                jsonObject.put("amount_per_note", result.amount_per_note);
                if (result.amount_per_note == 0) {
                    Utils.showToast("单注金额不能为0");
                    return;
                }
                jsonObject.put("note_count", result.num);
                jsonObject.put("odds", result.odds);
                jsonObject.put("rakeback", result.rakeback);
                jsonObject.put("is_follow", 0);
                jsonObject.put("is_win_stop", 0);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            jsonArray.put(jsonObject);
        }

        RetrofitBase.getRetrofit().create(CreateOrderRequest.class).getResult(jsonArray, UserInfo.getToken(), null)
                .compose(RxHelper.<CreateOrderResponse>handleResult())
                .subscribe(new RxSubscribe<CreateOrderResponse>(this) {
                    @Override
                    protected void _onNext(CreateOrderResponse createOrderResponse) {
                        IToastAddBet.show(getApplicationContext());
                        Utils.showToast("余额为" + createOrderResponse.getAfter_amount() + "元");

                        results.clear();

                        AddBetSuccess addBetSuccess = new AddBetSuccess();
                        addBetSuccess.setAfter_amount(createOrderResponse.getAfter_amount());
                        EventBus.getDefault().post(addBetSuccess);
                    }



                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        if (UserInfo.getIsTest() == 1 && UserInfo.getIsTry() != 1){
                            IToast.show(e.getMessage(),BetListActivity.this);
                        }else {
                            if (e.getMessage().equals("余额不足")){
                                Utils.createDialog(BetListActivity.this, "余额不足，是否去充值？", "去充值", "取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        Intent intent1 = new Intent(BetListActivity.this, ChargeActivity.class);
                                        startActivity(intent1);
                                    }
                                }, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {

                                    }
                                });
                            }else {
                                IToast.show(e.getMessage(),BetListActivity.this);
                            }
                        }

                    }






                    @Override
                    public boolean showDialog() {
                        return true;
                    }
                });
    }

    public void setMoney() {
        sumMoney = 0;
        int totalCount = 0;
        for (Result result1 : results.getList()) {
            sumMoney += result1.money;
            totalCount += result1.num;
        }

        money.setText(totalCount + "注" + Utils.saveTwoFormat(sumMoney) + "元");
    }

    public static void addOneNote(String temp_result,
                                  String temp_name,
                                  int temp_num,
                                  float temp_money,
                                  float temp_amount_per_note,
                                  String temp_checkbox_string,
                                  String temp_rule_id,
                                  String temp_rakeback,
                                  String temp_odds,
                                  Serializable object,
                                  float temp_max_rakeback,
                                  String max_odds,
                                  String theory_odds,
                                  float max_profit,
                                  String min_profit,
                                  float min_rakeback,
                                  String code,
                                  String layout_code) {
        Result result = new Result();
        result.result = temp_result;
        result.name = temp_name;
        result.num = temp_num;
        result.money = temp_money;
        result.amount_per_note = temp_amount_per_note;
        result.checkbox_string = temp_checkbox_string;
        result.rule_id = temp_rule_id;
        result.rakeback = temp_rakeback;
        result.odds = temp_odds;
        result.childrenBean = (GetLotteryDetailResponse.LayoutsBean.ChildrenBeanX.ChildrenBean) object;
        if (result.checkbox_string == null || result.checkbox_string.equals("")) {
            result.show_results = result.result;
        } else {
            result.show_results = result.checkbox_string + "|" + result.result;
        }
        result.max_rakeback = temp_max_rakeback;

        Gson gson = new Gson();
        Type entityType = new TypeToken<LinkedHashMap>() {
        }.getType();
        result.max_odds = gson.fromJson(max_odds, entityType);
        result.theory_odds = gson.fromJson(theory_odds, entityType);
        result.max_profit = max_profit;
        result.min_profit = min_profit;
        result.min_rakeback = min_rakeback;
        if ("ahk3".equals(code) || "jiangsuk3".equals(code)) {
            if ("hezhi_hezhi_hezhi".equals(layout_code)) {
                String[] re = result.result.split(",");
                List<String> keyList = new ArrayList<String>(result.max_odds.keySet());
                result.odds = null;
                String[] temp = temp_odds.split(",");
                for (String aRe : re) {
                    int index = keyList.indexOf(aRe);
                    if (result.odds == null) {
                        result.odds = temp[index];
                    } else {
                        result.odds = result.odds + "," + temp[index];
                    }
                }
            }
        }
        results.add(result);

        lastResult = result;
    }

    private void init() {
        recordMoneyList = new ArrayList<>();
        mBottomButtonModule = new BottomButtonModule(this,
                new Function0<Unit>() {
                    @Override
                    public Unit invoke() {
                        if (results.size() > 0) {
                            if (currentNo.equals(getIntent().getLongExtra("no", 0) + "")) {
                                addBet();
                            } else {
                                Dialog dialog = new AlertDialog.Builder(BetListActivity.this)
                                        .setMessage("期次已变化，当前是" + currentNo + "期，是否继续投注？")//设置提示内容
                                        //确定按钮
                                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                addBet();
                                            }
                                        })
                                        //取消按钮
                                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {

                                            }
                                        })
                                        .create();//创建对话框
                                if (Utils.isActivityRunning(BetListActivity.this)) {
                                    dialog.show();//显示对话框
                                }
                            }
                        } else {
                            Utils.showToast("您的注数为空");
                        }
                        return null;
                    }
                },
                new Function1<String, Unit>() {
                    @Override
                    public Unit invoke(String s) {
                        for (Result results : results.getList()) {
                            if (s.length() == 0) {
                                results.amount_per_note = 0;
                            } else {
                                results.amount_per_note = Float.parseFloat(s);
                            }
                            results.money = results.num * results.amount_per_note;
                        }

                        if (betListAdapter != null) {
                            betListAdapter.notifyDataSetChanged();
                        }

                        setMoney();
                        return null;
                    }
                },
                new Function0<Unit>() {
                    @Override
                    public Unit invoke() {
                        for (int i = 0; i < results.size(); i++) {
                            results.getList().get(i).amount_per_note = recordMoneyList.get(i);
                            results.getList().get(i).money = results.getList().get(i).amount_per_note * results.getList().get(i).num;
                        }

                        if (betListAdapter != null) {
                            betListAdapter.notifyDataSetChanged();
                        }

                        setMoney();
                        return null;
                    }
                });

        webview.getSettings().setJavaScriptEnabled(true);
        webview.loadUrl("file:///android_asset/count.html");
        webview.addJavascriptInterface(this, "MyCount");

        EventBus.getDefault().register(this);

        currentNo = getIntent().getLongExtra("no", 0) + "";

        httpCurrentIssueNoData();
        countDown();

        if (!getIntent().getBooleanExtra("shopping_car", false)) {
            addOneNote(getIntent().getStringExtra("result"),
                    getIntent().getStringExtra("name"),
                    getIntent().getIntExtra("num", 0),
                    getIntent().getFloatExtra("money", 0),
                    getIntent().getFloatExtra("amount_per_note", 0),
                    getIntent().getStringExtra("checkBoxString"),
                    getIntent().getStringExtra("rule_id"),
                    getIntent().getStringExtra("rakeback"),
                    getIntent().getStringExtra("odds"),
                    getIntent().getSerializableExtra("object"),
                    getIntent().getFloatExtra("max_rakeback", 0),
                    getIntent().getStringExtra("max_odds"),
                    getIntent().getStringExtra("theory_odds"),
                    getIntent().getFloatExtra("max_profit", 0),
                    getIntent().getStringExtra("min_profit"),
                    getIntent().getFloatExtra("min_rakeback", 0),
                    getIntent().getStringExtra("code"),
                    getIntent().getStringExtra("layout_code"));
        }

        setMoney();

        betListAdapter = new BetListAdapter(this);
        listView.setAdapter(betListAdapter);

        for (Result results : results.getList()) {
            recordMoneyList.add(results.amount_per_note);
        }
    }

    private void countDown() {
        countDownModel = new CountDownManager.CountDownModel() {
            public boolean isLoad;

            @Override
            public void onExecute() {
                if (currentIssueNoData != null) {
                    currentIssueNoData.setTime(currentIssueNoData.getTime() - 1);
                    if (currentIssueNoData.getTime() >= 0) {
                        isLoad = false;
                        time.setText(Html.fromHtml("第" + currentNo + "期截止时间  " + "<font color='#3f3f3f'>" + Utils.getCountTimeByLong(currentIssueNoData.getTime() * 1000) + "</font>"));
                    } else {
                        if (!isLoad) {
                            isLoad = true;
                            time.setText(Html.fromHtml("第" + currentIssueNoData.getNo() + "期截止时间  " + "<font color='#3f3f3f'>" + "00:00:00" + "</font>"));
                            httpCurrentIssueNoData();
                        }
                    }
                }
            }
        };
        CountDownManager.asInstance().register(countDownModel);
    }


    private void httpCurrentIssueNoData() {
        RetrofitBase.getRetrofit().create(GetCurrentIssueNoRequest.class).getResult(getIntent().getStringExtra("code"))
                .compose(RxHelper.<GetCurrentIssueNoResponse>handleResultReConnection())
                .subscribe(new RxSubscribe<GetCurrentIssueNoResponse>(this) {
                    @Override
                    protected void _onNext(final GetCurrentIssueNoResponse getCurrentIssueNoResponse) {
                        currentIssueNoData = getCurrentIssueNoResponse;
                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }
                });
    }

    public String getProfit(Result result) {
        if (Utils.isNumeric(result.odds)) {
            float profit = result.money * (Float.parseFloat(result.odds) - 1) + Float.parseFloat(result.rakeback) / 100 * result.money;
            BigDecimal b = new BigDecimal(profit);
            return b.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
        } else {
            float max = 0;
            List<String> floats = Arrays.asList(result.odds.split(","));
            for (String s : floats) {
                float f = Float.parseFloat(s);
                if (max < f) {
                    max = f;
                }
            }
            float profit = result.money * (max - 1) + Float.parseFloat(result.rakeback) / 100 * result.money;
            BigDecimal b = new BigDecimal(profit);
            return b.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
        }
    }

    public void openOrderSet(Result result, int position) {
        OrderSetDialog orderSetDialog = new OrderSetDialog();
        Bundle bundle = new Bundle();
        bundle.putString("status2", getIntent().getStringExtra("status2"));
        bundle.putInt("type", 1);
        bundle.putFloat("moneyPerStack", 2);
        bundle.putFloat("unit", 1);
        bundle.putFloat("max_rakeback", result.max_rakeback);
        bundle.putSerializable("max_odds", result.max_odds);
        bundle.putSerializable("theory_odds", result.theory_odds);
        bundle.putFloat("max_profit", result.max_profit);
        bundle.putString("min_profit", result.min_profit);
        bundle.putFloat("min_rakeback", result.min_rakeback);
        bundle.putInt("num", result.num);
        bundle.putInt("position", position);

        orderSetDialog.setArguments(bundle);
        FragmentTransaction fts = getSupportFragmentManager().beginTransaction();
        fts.replace(android.R.id.content, orderSetDialog);
        fts.setCustomAnimations(R.anim.anim_enter_from_top, 0);
        fts.addToBackStack(null);
        fts.commitAllowingStateLoss();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);
    }

    @Override
    public void finish() {
        if (results.size() > 0) {
            Utils.showToast("投注单已添加到购物车里");
        }

        EventBus.getDefault().post(new AddBetList());

        super.finish();
    }
}